#include <string>
#include "TcpConnection.h"
#include "Log.h"

int32_t TcpConnection::processRead(void *arg)
{
    TcpConnection *conn = (TcpConnection *)arg;
    // 接收数据
    int socket = conn->m_channel->getSocket();
    int count = conn->m_readBuff->socketRead(socket);
    if (count > 0)
    {
        printf("processRead 函数调用 cfd = %d\n", socket);
        printf("bufferSocketRead 函数调用 cfd = %d 读取count = %d\n", socket, count);

#ifdef MSG_SEND_AUTO
        conn->m_channel->writeEventEnable(true);
        conn->m_evLoop->addTask(conn->m_channel, ElemType::MODIFY);
#endif
        bool flag = conn->m_request->parseRequest(conn->m_readBuff, conn->m_response, conn->m_writeBuff, socket);
        if (!flag)
        {
            // 解析失败,回复一个简单的html
            const char *errMsg = "Http/1.1 400 Bad Request\r\n\r\n";
            conn->m_writeBuff->appendString(errMsg);
        }
    }
#ifndef MSG_SEND_AUTO
    conn->m_evLoop->addTask(conn->m_channel, ElemType::DELECT);
#endif
    return 0;
}

int32_t TcpConnection::destroy(void *arg)
{
    TcpConnection *conn = (TcpConnection *)arg;
    if(conn != nullptr)
    {
        delete conn;
    }
    return 0;
}

int32_t TcpConnection::processWrite(void *arg)
{
    printf("processWrite 函数调用\n");
    TcpConnection *conn = (TcpConnection *)arg;
    // 发送数据
    int socket = conn->m_channel->getSocket();
    int count = conn->m_writeBuff->socketRead(socket);
    if (count > 0)
    {
        // 判断数据是否全部发送出去了
        if (conn->m_writeBuff->readableSize() == 0)
        {
            // 1.不再检测写事件 -- 修改channel中保存的事件
            conn->m_channel->writeEventEnable(false);
            // 2.修改dispatcher检测的集合 -- 添加任务节点
            conn->m_evLoop->addTask(conn->m_channel, ElemType::MODIFY);
            // 3.删除这个节点
            conn->m_evLoop->addTask(conn->m_channel, ElemType::DELECT);
        }
    }
    else
    {
            conn->m_evLoop->addTask(conn->m_channel, ElemType::DELECT);
    }
    return 0;
}

TcpConnection::TcpConnection(int32_t fd, EventLoop *evLoop)
{
    m_name = "Connecttion-" + std::to_string(fd);
    m_evLoop = evLoop;
    m_request = new HttpRequest();
    m_response = new HttpResponse();
    m_readBuff = new Buffer(10240);
    m_writeBuff = new Buffer(10240);

    m_channel = new Channel(fd, FDEvent::ReadEvent, &TcpConnection::processRead, &TcpConnection::processWrite, destroy, this);
    m_evLoop->addTask(m_channel, ElemType::ADD);
}

TcpConnection::~TcpConnection()
{
        if (m_readBuff && m_readBuff->readableSize() == 0 && m_writeBuff && m_writeBuff->writeableSize() == 0)
        {
            delete m_readBuff;
            delete m_writeBuff;
            delete m_readBuff;
            delete m_response;
            m_evLoop->freeChannel(m_channel);
        }
}
